package mytools;

import android.app.DownloadManager;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.hardware.bcreader.BCRManager;
import android.os.Bundle;
import android.os.Environment;
import android.preference.PreferenceManager;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.util.ArrayMap;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.socks.library.KLog;

import java.io.File;
import java.io.IOException;
import java.util.Calendar;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

import broadcastreceiver.DownLoadReceiver;
import dialogui.ProgressDialogFragment;
import gov.kqqzyyy.monkey.ydhl.ui.PatientDetailActivity;
import objects.InPatient;
import objects.InPatient_BRBS;
import objects.OrderDetail;
import objects.Section;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by Monkey on 2017/10/23.
 * 自定义基Activity
 */
public class MyBaseActivity extends AppCompatActivity {

    private SwipeRefreshLayout swipeRefreshLayout;

    private ProgressDialogFragment progressDialogFragment;

    private MyApplication myApplication;
    private SharedPreferences mySharedPreferences;

    private DownLoadReceiver downLoadReceiver;

    private UploadListener uploadListener;
    private boolean isUploading = false;
    private Thread ftpThread;

    private BCRManager mBCRManager;

    private Call<String> sbxhCall;
    private Call<String> yzjhCall;
    private Call<String> brbsCall;

    private List<OrderDetail> mYZJHList;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        myApplication = (MyApplication) getApplication();
        mySharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
        downLoadReceiver = new DownLoadReceiver();
        IntentFilter intentFilter = new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
        this.registerReceiver(downLoadReceiver, intentFilter);
        uploadListener = (currentStep, uploadSize, file) -> {
            KLog.d("APE", currentStep);
            switch (currentStep) {
                case FtpUtil.FTP_UPLOAD_SUCCESS:
                    KLog.d("APE", file.getName() + FtpUtil.FTP_UPLOAD_SUCCESS);
                    break;
                case FtpUtil.FTP_UPLOAD_LOADING:
                    long fize = file.length();
                    float num = (float) uploadSize / (float) fize;
                    int result = (int) (num * 100);
                    KLog.d("APE", FtpUtil.FTP_UPLOAD_LOADING + ":" + result);
                    break;
                case FtpUtil.FTP_DISCONNECT_SUCCESS:
                    stopUploadThread();
                    break;
                case FtpUtil.FTP_CONNECT_FAIL:
                    KLog.d("APE", FtpUtil.FTP_CONNECT_FAIL);
                    break;
                case FtpUtil.FTP_UPLOAD_FAIL:
                    KLog.d("APE", FtpUtil.FTP_UPLOAD_FAIL);
                    break;
            }
        };
        mBCRManager = BCRManager.getInstance();
    }

    @Override
    protected void onStop() {
        super.onStop();
        mBCRManager.stopScan();
        if (sbxhCall != null && sbxhCall.isExecuted()) {
            sbxhCall.cancel();
        }
        if (yzjhCall != null && yzjhCall.isExecuted()) {
            yzjhCall.cancel();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mBCRManager.isReady()) {
            mBCRManager.close();
        }
        unregisterReceiver(downLoadReceiver);
        System.gc();
    }

    public BCRManager getmBCRManager() {
        return mBCRManager;
    }

    public MyApplication getMyApplication() {
        return myApplication;
    }

    public SharedPreferences getMySharedPreferences() {
        return mySharedPreferences;
    }

    public void cancelProgressDialog() {
        if (progressDialogFragment != null && progressDialogFragment.getDialog() != null) {
            progressDialogFragment.getDialog().dismiss();
        }
    }

    public void showProgressDialog(String message) {
        cancelProgressDialog();
        progressDialogFragment = new ProgressDialogFragment();
        progressDialogFragment.setMessage(message);
        progressDialogFragment.show(getFragmentManager(), "downLoading");
    }

    private void stopUploadThread() {
        isUploading = false;
        if (ftpThread != null && ftpThread.isAlive()) {
            ftpThread.interrupt();
            ftpThread = null;
        }
    }

    private LinkedList<File> doGetUploadFiles() {
        String logPath = Environment.getExternalStorageDirectory().getAbsolutePath()
                + File.separator + "crash" + File.separator;
        File crashDir = new File(logPath);
        Date deleDate;
        Calendar calendar = Calendar.getInstance();
        calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DATE) - 1);
        String deletaDateString = DateUtil.getDateFormat(calendar.getTime());

        deleDate = DateUtil.getDFormatDate(deletaDateString);
        if (crashDir.isDirectory()) {
            File[] files = crashDir.listFiles();
            LinkedList<File> fileList = new LinkedList<>();
            for (File file : files
                    ) {
                String fileName = file.getName();
                if (fileName.contains(".log") && fileName.startsWith("wtvs-")) {
                    String fileDateString = fileName.substring(5, 15);
                    Date fileDate = DateUtil.getDFormatDate(fileDateString);
                    if (fileDate.getTime() < deleDate.getTime()) {
                        fileList.add(file);
                    }
                }
            }
            KLog.d("APE", fileList.size());
            return fileList;
        }
        return null;
    }

    public void doUploadLogFile() {
        final LinkedList<File> fileList = doGetUploadFiles();
        if (fileList != null && fileList.size() > 0) {
            if (!isUploading) {
                isUploading = true;
                ftpThread = new Thread(() -> {
                    while (isUploading) {
                        try {
                            new FtpUtil().uploadMultiFile(fileList, uploadListener, true);
                        } catch (IOException e) {
                            stopUploadThread();
                            KLog.d("APE", e.getMessage());
                            e.printStackTrace();
                        }
                    }
                });
                ftpThread.start();
            }
        } else {
            Toast.makeText(getApplicationContext(), "没有需要上传的日志！", Toast.LENGTH_SHORT).show();
        }
    }

    public void setSwipeRefreshLayout(SwipeRefreshLayout swipeRefreshLayout) {
        this.swipeRefreshLayout = swipeRefreshLayout;
    }

    public void stopRefreshing() {
        if (swipeRefreshLayout != null && swipeRefreshLayout.isNestedScrollingEnabled()) {
            swipeRefreshLayout.setRefreshing(false);
        }
    }

    public List<OrderDetail> getmYZJHList() {
        return mYZJHList;
    }

    //获取医嘱计划
    public void doGetYZJH(boolean showProgress, String zyh, String startDate, String endDate) {
        if (showProgress) {
            showProgressDialog("获取医嘱信息中");
        }
        yzjhCall = MyServiceUtil.getYZJHCall(zyh, startDate, endDate);
        Callback<String> callback = new Callback<String>() {
            @Override
            public void onResponse(Call<String> call, Response<String> response) {
                cancelProgressDialog();
                stopRefreshing();
                String result = response.body();
                if (result != null) {
                    Gson gson = new Gson();
                    mYZJHList = gson.fromJson(result, new TypeToken<List<OrderDetail>>() {
                    }.getType());
//                    if (mYZJHList != null && mYZJHList.size() > 0) {
//                        Collections.sort(mYZJHList, (arg0, arg1) -> arg1.getYZZX().compareTo(arg0.getYZZX()));
//                    }

                    //获取医嘱计划成功 ，下一步操作

                }
            }

            @Override
            public void onFailure(Call<String> call, Throwable t) {
                cancelProgressDialog();
                stopRefreshing();
                Toast.makeText(getApplicationContext(), "获取医嘱信息失败!", Toast.LENGTH_LONG).show();
            }
        };
        yzjhCall.enqueue(callback);
    }

    //获取设备序号
    public void doGetSBXH(String sbbs, String ipdz, String bzxx) {
        sbxhCall = MyServiceUtil.getSBXHCall(sbbs, ipdz, bzxx);
        Callback<String> callback = new Callback<String>() {
            @Override
            public void onResponse(Call<String> call, Response<String> response) {
                String result = response.body();
                if (result != null) {
                    result = result.replaceAll("\"", "");
                    mySharedPreferences.edit().putString("SBXH", result).apply();
                }
            }

            @Override
            public void onFailure(Call<String> call, Throwable t) {
                Toast.makeText(getApplicationContext(), "获取设备信息失败，确保服务器地址正确后重试！", Toast.LENGTH_SHORT).show();
            }
        };
        sbxhCall.enqueue(callback);
    }

    //扫描标识获取病人
    public void getPatientByBRBS(String brbs) {
        showProgressDialog("获取扫描病人中");
        brbsCall = MyServiceUtil.getBrbsPatientCall(brbs);
        Callback<String> callback = new Callback<String>() {
            @Override
            public void onResponse(Call<String> call, Response<String> response) {
                String result = response.body();
                if (result != null) {
                    Gson gson = new Gson();
                    List<InPatient_BRBS> list = gson.fromJson(result, new TypeToken<List<InPatient_BRBS>>() {
                    }.getType());
                    if (list != null && list.size() > 0) {
                        doFindScanPatient(list.get(0));
                    }
                }
                cancelProgressDialog();
            }

            @Override
            public void onFailure(Call<String> call, Throwable t) {
                cancelProgressDialog();
            }
        };
        brbsCall.enqueue(callback);
    }

    //在当前病区病人列表寻找扫描病人
    private void doFindScanPatient(InPatient_BRBS scanPatient) {
        Section section = getMyApplication().getCurrentSection();
        ArrayMap<Section, List<InPatient>> dataMap = getMyApplication().getmDataMap();
        boolean isFound = false;
        if (section != null && dataMap != null) {
            List<InPatient> list = dataMap.get(section);
            if (list != null && list.size() > 0) {
                for (InPatient patient : list
                        ) {
                    if (patient.getZYH().equals(scanPatient.getZYH())) {
                        getMyApplication().setChoosePatient(patient);
                        //找到病人操作
                        isFound = true;
                        Intent intent = new Intent(getApplicationContext(), PatientDetailActivity.class);
                        startActivity(intent);
                        break;
                    }
                }
                if (!isFound) {
                    Toast.makeText(getApplicationContext(), "当前病区没有该病人，请切换到对应病区！", Toast.LENGTH_SHORT).show();
                }
            }
        }


    }
}
